#pragma once
#include <functional>
#include "Common.hpp"
#include "Socket.hpp"
#include "Log.hpp"
using namespace SocketModule;
using namespace LogModule;

using func_t  = std::function<void(std::shared_ptr<Socket>& sockfd, InetAddr& client)>;

//服务器在启动前自动初始化
class TcpServer : public NoCopy
{
public:
    TcpServer( uint16_t port, func_t fun)
        :_func(fun)
        ,_isrunning(false)
        ,_listenfd(std::make_unique<TcpSocket>())
        ,_port(port)
    {
        _listenfd->Init(_port);
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            //1.与客户端建立连接， 此时如果有客户端请求通信，服务端会将客户端丢入连接队列
            InetAddr client;
            std::shared_ptr<Socket> sockfd = _listenfd->Accept(&client);
            if(sockfd == nullptr)
                continue;
            
            //2.到这已经有一个客户端与服务端建立了连接，接下来创建子进程处理业务，父进程继续接收
            pid_t id = fork();
            if(id <= 0)
                exit(FORK_ERROR);
            else if (id == 0)
            {
                if(fork())
                    exit(OK);
                _func(sockfd,client);
                sockfd ->Close();
                exit(OK);
            }
            else
            {
                pid_t rid = ::waitpid(id,nullptr,0);
                (void)rid;

            }
        }
        _isrunning = false;
    }

private:
    std::unique_ptr<Socket> _listenfd;
    bool _isrunning;
    func_t _func;
    uint16_t _port;
};